<template>
  <div class="skills-management tech-page">
    <dv-border-box-12 class="tech-header-box">
      <div class="tech-header">
        <h2 class="tech-title">技能管理</h2>
        <el-button type="primary" class="tech-button tech-button--primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增技能
        </el-button>
      </div>
    </dv-border-box-12>

    <dv-border-box-8 class="tech-search-box">
      <div class="tech-search-bar">
        <el-form :inline="true" :model="searchForm" class="tech-search-form">
          <el-form-item label="标题">
            <el-input v-model="searchForm.title" placeholder="请输入标题" clearable />
          </el-form-item>
          <el-form-item label="标签">
            <el-input v-model="searchForm.tag" placeholder="请输入标签" clearable />
          </el-form-item>
          <el-form-item label="内容">
            <el-input v-model="searchForm.content" placeholder="请输入内容" clearable />
          </el-form-item>
          <el-form-item label="摘要">
            <el-input v-model="searchForm.summary" placeholder="请输入摘要" clearable />
          </el-form-item>
          <el-form-item label="状态" class="status-form-item">
            <el-select v-model="searchForm.enableStatus" placeholder="请选择状态" clearable class="status-select">
              <el-option value="enabled" label="启用">
                <div class="status-option">
                  <span class="status-dot status-dot--enabled"></span>
                  <span>启用</span>
                </div>
              </el-option>
              <el-option value="disabled" label="禁用">
                <div class="status-option">
                  <span class="status-dot status-dot--disabled"></span>
                  <span>禁用</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="tech-button tech-button--primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button class="tech-button" @click="resetSearch">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </dv-border-box-8>

    <dv-border-box-10 class="tech-table-box">
      <div class="tech-table-container">
        <el-table
          v-loading="loading"
          :data="tipsList"
          style="width: 100%"
          class="tech-table"
          element-loading-text="数据加载中..."
          element-loading-background="rgba(0, 20, 40, 0.8)"
        >
          <el-table-column prop="id" label="ID" min-width="100" show-overflow-tooltip />
          <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip />
          <el-table-column prop="tag" label="标签" min-width="120" show-overflow-tooltip />
          <el-table-column prop="summary" label="摘要" min-width="200" show-overflow-tooltip />
          <el-table-column prop="content" label="内容" min-width="250" show-overflow-tooltip />
          <el-table-column prop="date" label="日期" min-width="120" show-overflow-tooltip />
          <el-table-column prop="views" label="浏览量" min-width="100" show-overflow-tooltip />
          <el-table-column prop="likes" label="点赞数" min-width="100" show-overflow-tooltip />
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <div class="status-tag-container">
                <el-tag
                  :type="scope.row.enable === false ? 'danger' : 'success'"
                  effect="dark"
                  size="small"
                  class="status-tag"
                >
                  <div class="status-content">
                    <span class="status-dot" :class="scope.row?.enable?'status-dot--enabled': 'status-dot--disabled' "></span>
                    <span>{{ scope.row.enable === false ? '禁用' : '启用' }}</span>
                  </div>
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" class="tech-button tech-button--primary" @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button 
                :type="scope.row.enable === false ? 'success' : 'warning'"
                size="small" 
                class="tech-button" 
                :class="scope.row.enable === false ? 'tech-button--success' : 'tech-button--warning'"
                @click="handleToggleStatus(scope.row)"
              >
                <el-icon v-if="scope.row.enable === false"><Check /></el-icon>
                <el-icon v-else><Close /></el-icon>
                {{ scope.row.enable === false ? '启用' : '禁用' }}
              </el-button>
              <el-button type="danger" size="small" class="tech-button tech-button--danger" @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="tech-pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            prev-text="上一页"
            next-text="下一页"
            :pager-count="7"
          >
            <template #total>
              共 {{ total }} 条记录
            </template>
            <template #sizes>
              每页 {{ pageSize }} 条
            </template>
          </el-pagination>
        </div>
      </div>
    </dv-border-box-10>
    <!-- 技能表单对话框 -->
    <SkillFormDialog
      v-model:visible="dialogVisible"
      :skill-data="currentSkill"
      @refresh="fetchTipsList"
    />
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete, Check, Close } from '@element-plus/icons-vue'
import { app, ensureLogin } from '../../utils/cloudbase'
import SkillFormDialog from '../../components/skills/SkillFormDialog.vue'

export default {
  name: 'SkillsManagement',
  components: {
    Plus,
    Search,
    Refresh,
    Edit,
    Delete,
    Check,
    Close,
    SkillFormDialog
  },
  setup() {
    // 搜索表单
    const searchForm = reactive({
      title: '',
      tag: '',
      content: '',
      summary: '',
      enableStatus: ''
    })

    // 表格数据
    const loading = ref(false)
    const tipsList = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    // 初始化数据
    onMounted(() => {
      fetchTipsList()
    })

    // 获取技能列表
    const fetchTipsList = async () => {
      console.log('执行刷新列表')
      loading.value = true
      try {
        // 确保用户已登录
        await ensureLogin()
        
        // 构建查询参数
        const queryParams = {
          page: currentPage.value,
          pageSize: pageSize.value
        }
        
        if (searchForm.title) {
          queryParams.title = searchForm.title
        }
        
        if (searchForm.tag) {
          queryParams.tag = searchForm.tag
        }
        
        if (searchForm.content) {
          queryParams.content = searchForm.content
        }
        
        if (searchForm.summary) {
          queryParams.summary = searchForm.summary
        }
        
        if (searchForm.enableStatus) {
          queryParams.enableStatus = searchForm.enableStatus
        }
        
        // 调用云函数
        let res;
        try {
          res = await app.callFunction({
            name: 'admin-skills-list-crud',
            data: {
              action: 'list',
              data: queryParams
            }
          });
        } catch (callError) {
          console.error('调用云函数失败:', callError);
          res = { result: { code: -1, message: '调用云函数失败' } };
        }
        
        const result = res.result || {}
        
        if (result.code === 0) {
          tipsList.value = result.data.list || []
          total.value = result.data.total || 0
        } else {
          ElMessage.error(result.message || '获取简历提示列表失败')
          tipsList.value = []
          total.value = 0
        }
      } catch (error) {
        console.error('获取简历提示列表失败:', error)
        ElMessage.error('获取简历提示列表失败')
        tipsList.value = []
        total.value = 0
      } finally {
        loading.value = false
      }
    }

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchTipsList()
    }

    // 重置搜索
    const resetSearch = () => {
      searchForm.title = ''
      searchForm.tag = ''
      searchForm.content = ''
      searchForm.summary = ''
      searchForm.enableStatus = ''
      handleSearch()
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchTipsList()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchTipsList()
    }

    // 对话框相关
    const dialogVisible = ref(false)
    const currentSkill = ref(null)

    // 新增技能
    const handleAdd = () => {
      currentSkill.value = null
      dialogVisible.value = true
    }

    // 编辑技能
    const handleEdit = (row) => {
      currentSkill.value = row
      dialogVisible.value = true
    }

    // 切换技能状态
    const handleToggleStatus = async (row) => {
      const newStatus = row.enable === false
      const statusText = newStatus ? '启用' : '禁用'
      
      try {
        // 确保用户已登录
        await ensureLogin()
        
        // 调用云函数
        const res = await app.callFunction({
          name: 'admin-skills-list-crud',
          data: {
            action: 'update',
            data: { 
              _id: row._id,
              enable: newStatus
            }
          }
        })
        
        const result = res.result || {}
        
        if (result.code === 0) {
          ElMessage.success(`${statusText}成功`)
          // 更新本地数据
          row.enable = newStatus
        } else {
          ElMessage.error(result.message || `${statusText}失败`)
        }
      } catch (error) {
        console.error(`${statusText}技能失败:`, error)
        ElMessage.error(`${statusText}技能失败`)
      }
    }
    
    // 删除技能
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除技能 "${row.title}" 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'datav-message-box'
        }
      ).then(async () => {
        try {
          // 确保用户已登录
          await ensureLogin()
          
          // 调用云函数
          const res = await app.callFunction({
            name: 'admin-skills-list-crud',
            data: {
              action: 'delete',
              data: { _id: row._id }
            }
          })
          
          const result = res.result || {}
          
          if (result.code === 0) {
            ElMessage.success('删除成功')
            fetchTipsList()
          } else {
            ElMessage.error(result.message || '删除失败')
          }
        } catch (error) {
          console.error('删除技能失败:', error)
          ElMessage.error('删除技能失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }

    return {
      searchForm,
      loading,
      tipsList,
      currentPage,
      pageSize,
      total,
      dialogVisible,
      currentSkill,
      fetchTipsList,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleDelete,
      handleToggleStatus
    }
  }
}
</script>

<style scoped>
.skills-management {
  padding: 0;
}

/* 状态选择器样式 */
.status-form-item {
  margin-right: 10px;
}

.status-select {
  width: 120px;
  background-color: rgba(0, 30, 60, 0.6);
  border-radius: 4px;
}

:deep(.status-select .el-input__wrapper) {
  background-color: rgba(0, 30, 60, 0.6);
  box-shadow: 0 0 0 1px rgba(0, 192, 255, 0.3) inset;
  border-radius: 4px;
  backdrop-filter: blur(5px);
}

:deep(.status-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px rgba(0, 192, 255, 0.5) inset;
}

:deep(.status-select .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px rgba(0, 192, 255, 0.7) inset;
}

:deep(.status-select .el-input__inner) {
  color: #ffffff;
}

:deep(.el-select__popper) {
  background-color: rgba(0, 19, 47, 0.95) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
  backdrop-filter: blur(10px);
}

:deep(.el-select-dropdown__item) {
  color: #ffffff;
}

:deep(.el-select-dropdown__item.hover) {
  background-color: rgba(0, 192, 255, 0.2) !important;
}

:deep(.el-select-dropdown__item.selected) {
  background-color: rgba(0, 192, 255, 0.3) !important;
  color: #00c0ff;
}

/* 状态点样式 */
.status-option {
  display: flex;
  align-items: center;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}

.status-dot--enabled {
  background-color: #67c23a;
  box-shadow: 0 0 5px #67c23a;
}

.status-dot--disabled {
  background-color: #f56c6c;
  box-shadow: 0 0 5px #f56c6c;
}

/* 状态标签样式 */
.status-tag-container {
  display: flex;
  justify-content: center;
}

.status-tag {
  min-width: 60px;
  text-align: center;
}

.status-content {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 按钮样式 */
.tech-button--success {
  background-color: rgba(103, 194, 58, 0.2) !important;
  border-color: rgba(103, 194, 58, 0.7) !important;
  color: #67c23a !important;
}

.tech-button--success:hover {
  background-color: rgba(103, 194, 58, 0.4) !important;
  border-color: #67c23a !important;
  color: #ffffff !important;
}

.tech-button--warning {
  background-color: rgba(230, 162, 60, 0.2) !important;
  border-color: rgba(230, 162, 60, 0.7) !important;
  color: #e6a23c !important;
}

.tech-button--warning:hover {
  background-color: rgba(230, 162, 60, 0.4) !important;
  border-color: #e6a23c !important;
  color: #ffffff !important;
}

:deep(.datav-message-box) {
  background-color: rgba(0, 19, 47, 0.9) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
}

:deep(.datav-message-box .el-message-box__header) {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-bottom: 1px solid rgba(0, 192, 255, 0.3) !important;
}

:deep(.datav-message-box .el-message-box__title) {
  color: #00c0ff !important;
}

:deep(.datav-message-box .el-message-box__content) {
  background-color: rgba(0, 19, 47, 0.8) !important;
  color: #ffffff !important;
}

:deep(.datav-message-box .el-message-box__container) {
  padding: 15px !important;
}

:deep(.datav-message-box .el-message-box__footer) {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-top: 1px solid rgba(0, 192, 255, 0.3) !important;
}

:deep(.datav-message-box .el-button) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border-color: rgba(0, 192, 255, 0.3) !important;
  color: rgba(0, 192, 255, 0.8) !important;
}

:deep(.datav-message-box .el-button--primary) {
  background-color: rgba(0, 192, 255, 0.2) !important;
  border-color: rgba(0, 192, 255, 0.7) !important;
  color: #00c0ff !important;
}

:deep(.datav-message-box .el-button--primary:hover) {
  background-color: rgba(0, 192, 255, 0.4) !important;
  border-color: #00c0ff !important;
  color: #ffffff !important;
}
</style>
